import { watch } from 'vue'

import type { FP } from '../../types'

const useRefreshDepsPlugin: FP = (fetchInstance, { refreshDeps, refreshDepsAction, manual }) => {
  if (refreshDeps === undefined || (Array.isArray(refreshDeps) && refreshDeps.length === 0)) return {}

  const deps = Array.isArray(refreshDeps) ? refreshDeps : [refreshDeps]

  watch(deps, () => {
    if (refreshDepsAction) {
      refreshDepsAction()
    } else {
      !manual && fetchInstance.context.refresh()
    }
  })

  return {}
}

export default useRefreshDepsPlugin
